/**
 * Created by Freeman on 2016/8/1.
 */
import React, {Component, PropTypes} from 'react'
import TimeAgo from 'react-timeago'
import classnames from 'classnames'
import zhStrings from 'react-timeago/lib/language-strings/zh-CN'
import buildFormatter from 'react-timeago/lib/formatters/buildFormatter'

const formatter = buildFormatter(zhStrings)

class Messages extends Component {
    constructor(props, context) {
        super(props, context);
    }
    componentDidUpdate(){
        const messageList = this.refs.messageList;
        messageList.scrollTop = messageList.scrollHeight - messageList.clientHeight;
    }

    sessionUser () {
        let users = this.props.userList.items.filter(item => item.id === this.props.session.userId);
        return users[0];
    }
    time(date){
        if (typeof date === 'string') {
            date = new Date(date);
        }
        return date.getHours() + ':' + date.getMinutes();
    }
    avatar (item) {
        // 如果是自己发的消息显示登录用户的头像
        let user = item.self ? this.props.auth.user : this.sessionUser();
        return user && user.img;
    }
    renderMessage(items,sessionIndex){
        return (

            items[sessionIndex].messages.map(item =>
                <li key={item._id}>
                    <p className="time"><span>
                        <TimeAgo date={item.date} formatter={formatter}/>
                        </span></p>
                    <div className={
                        classnames({
                            self: item.self,
                            'main':true
                        })
                    } >
                        <img className="avatar" width="30" height="30" src={this.avatar(item)} />
                        <div className="text">{item.text}</div>
                    </div>
                </li>
            )

        )
    }

    render() {
        let {items,sessionIndex} = this.props.sessionList;
        return (
            <div className="m-message" ref="messageList">
                <ul>
                    {this.renderMessage(items,sessionIndex)}
                </ul>
            </div>
        )
    }
}

Messages.propTypes = {
    auth:PropTypes.object.isRequired,
    userList:PropTypes.object.isRequired,
    sessionList: PropTypes.object.isRequired,
    session: PropTypes.object.isRequired,
    actions:PropTypes.object.isRequired
};

export default Messages;